const cloud = require('wx-server-sdk')
const axios = require('axios')
const jwt = require('jsonwebtoken');
const option={
  algorithm:"HS256",
  expiresIn:"7day",
  issuer:"ChenBin"
}
const privateKey="ChenBin1786512286"
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const userDB=cloud.database().collection("user")
module.exports.login=async function(data){
  const wxContext = cloud.getWXContext()
  const {code,nackname,avatarUrl}=data
  console.log("data  ",data);
  // console.log("data  ",data);
  // const url=`https://api.weixin.qq.com/sns/jscode2session?appid=wxdcb3633fb74f492a&secret=944714ffbee02f5851f3e7af7d1699d7&js_code=${code}&grant_type=authorization_code`  
  // const {data:res}=await axios.get(url)
  // const {session_key,openid}=res
  // console.log("{session_key,openid}  ",{session_key,openid});
  // const {data:userRes}=await userDB.get()
  
  // console.log("解密",jwt.verify(token ,privateKey,this.option));  
  let addRes
  try{
    const openid=wxContext.OPENID
    const {data:[findID]}=await userDB.where({
      openid
    }).get()
    console.log("findID  ",findID);
    
    if(findID!==undefined){//直接登录
      console.log("登录返回token  ");
      const user={
        id:findID.id,
        openid:findID.openid
      }      
      let token=jwt.sign(user,privateKey,option)
      console.log("token  ",token);
      
      user.nackname=findID.nackname
      user.avatarUrl=findID.avatarUrl
      user.token=token
      delete user.openid
      return {
        code:0,
        msg:"登录成功",
        token,
        userInfo:user
      }
    }else{//注册登录
      const {total}=await userDB.count();
      const userInfo={
        id:total+1||Date.now(),
        openid,
      }
      let token=jwt.sign(userInfo,privateKey,option)
      let user={
        nackname,
        avatarUrl,
        role:"user"
      }
      Object.assign(user,userInfo)
      console.log("user  ",user);
      
      console.log("userInfo  ",userInfo);
      addRes=await userDB.add({data:user})
      user.token=token
      delete user.role
      delete user.openid
      return {
        code:0,
        msg:"注册成功已自动登录",
        userInfo:user
      }
    }    
  }catch(err){
    console.log("注册失败err  ",err);
    
    return {
      code:500,
      msg:"注册失败"
    }
  }
}
async function reg(){

}